<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>捷拉拉 简易个人聊天</title>
</head>
<body>
	<h1 style="text-align: center"> 捷拉拉 简易个人聊天</h1>
	<div class="wrap">
		<div>你的昵称：<input type="text" name="name" id="name" value="我是二二"  style="width:20%;height:25px;"> </div>
		<div>你的账号id：<input type="text" name="uid" id="uid" value="22"  style="width:20%;height:25px;"> </div>
		<div>接受者账号id：<input type="text" name="re_uid" id="re_uid" value="11"  style="width:20%;height:25px;"> </div>
		<button id='login-btn'>点击连接</button>
		<div style="color: deeppink;">温馨提示本页面，用于学习开发测试，请勿发送违法违禁的语言，ip等信息会被记录！文明聊天！</div>
		<div>本页面采用HTML+PHP后端+Swoole搭建的实时聊天</div>
		<div style="color: cadetblue;">个人</div>
		<div><textarea style="width:100%;height:450px;margin-top: 2px;" id="textShow" readonly></textarea></div>
		<p>内容：</p>
		<div style="text-align:center">
			<textarea style="width:100%;height:100px" id="textInput" placeholder="回车发送，shift+回车换行"></textarea>
			<button id="btnSend">发送</button>
		</div>

		<p style="font-size: 12px;"> <a href="https://qm.qq.com/cgi-bin/qm/qr?k=ByRJs6YYQ7YNLFQAu6ro_xpozxGI1UQd&amp;jump_from=webapi">点击加入PHP技术交流群153073132</a> </p>
	</div>
	
	<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
	<script>
        var wsUrl = 'ws://121.199.72.149:8081/ws'; // 修改为你的地址
		function getNowFormatDate() {
			var date = new Date();
			var seperator1 = "-";
			var seperator2 = ":";
			var month = date.getMonth() + 1;
			var strDate = date.getDate();
			if (month >= 1 && month <= 9) {
				month = "0" + month;
			}
			if (strDate >= 0 && strDate <= 9) {
				strDate = "0" + strDate;
			}
			var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
				+ " " + date.getHours() + seperator2 + date.getMinutes()
				+ seperator2 + date.getSeconds();
			return currentdate;
		}
		function fuckXSS(val) {
			var s = "";
			if(val.length == 0) return "";
			s = val.replace(/&/g,"&amp;");
			s = s.replace(/</g,"&lt;");
			s = s.replace(/>/g,"&gt;");
			s = s.replace(/ /g,"&nbsp;");
			s = s.replace(/\'/g,"&#39;");
			s = s.replace(/\"/g,"&quot;");
			return s;
		};
		$('#login-btn').click(function () {
			
			var btn_text =$('#login-btn').text()
			if(btn_text=='点击连接'){
				$('#login-btn').text('连接成功')
				var messageCache = [];
				// $('#name').val(RndNum(4));

				messageCache.push("连接中...\r\n");
				var ws = new WebSocket(wsUrl);
		
				ws.onopen = function(evt) {
					console.log(evt)
					messageCache.push("连接成功\r\n\r\n");
					login();
				};

				ws.onmessage = function(evt) {
					messageCache.push(getNowFormatDate() + "\r\n" + fuckXSS(evt.data.substring(0, 128)) + "\r\n\r\n");
				};

				setInterval(function(){
					if(0 === messageCache.length)
					{
						return;
					}
					var message = messageCache.join("\r\n");
					messageCache = [];
					if($('#textShow').text().length >= 512 * 1024)
					{
						$('#textShow').text("消息过多，已清屏\r\n");
					}

					if(message.length > 512 * 1024)
					{
						$('#textShow').append("瞬时消息过大，不显示……\r\n");
						return;
					}

					var isScroll = $('#textShow').innerHeight() + $('#textShow').scrollTop() === $('#textShow')[0].scrollHeight

					$('#textShow').append(decodeUnicode(message));

					if(isScroll)
					{
						$('#textShow').scrollTop($('#textShow')[0].scrollHeight);
					}
				}, 100); // 每100毫秒写入一次聊天记录
				
				ws.onclose = function(evt) {
					messageCache.push("后端代码更新中 稍后刷新重试\r\n");
					$('#login-btn').text('点击连接');

				};

				// 解码  
				function decodeUnicode(str) {  
					str = str.replace(/\\/g, "%");
					//转换中文
					str = unescape(str);
						//将其他受影响的转换回原来
					str = str.replace(/%/g, "\\");
						//对网址的链接进行处理
					str = str.replace(/\\/g, "");
					return str;
				}

				function sendContent()
				{
					var message = $('#textInput').val();
					var name = $('#name').val();
					var uid = $('#uid').val();
					var re_uid = $('#re_uid').val();
					if(message === '')
					{
						return;
					}
					// 发送
					var data = {
						action: 'send_user',//2个用户聊天    
						username: name,//昵称不重要
						uid: uid,//自己的uid
						re_uid: re_uid,//接收者的uid
						message: message,//消息内容
						type:'1',//类型 1=普通文本消息     2=心跳  3 订单号    4商家确认报价给用户   5用户确认报价    6用户评价订单
					};
					ws.send(JSON.stringify(data));
					$('#textInput').focus().val('');
				}
				function RndNum(n){   
			
				var rnd="";   
					
				for(var i=0;i<n;i++)   
					
				rnd+=Math.floor(Math.random()*10);   
					
				return rnd;   
					
				} 



				function login()
				{
					var message = 'login';//$('#textInput').val();
					var name = $('#name').val();
					var uid = $('#uid').val();
					var re_uid = $('#re_uid').val();
					if(message === '')
					{
						return;
					}
					// 发送
					var data = {
						action: 'im.joinSysRoom',
						username: name,
						uid: uid,
						re_uid: re_uid,
						message: message,
					};
					ws.send(JSON.stringify(data));
					$('#textInput').focus().val('');
				}

				$('#btnSend').click(sendContent);
				$('#textInput').on('keydown', function(e){
					if(e.keyCode == 13 && (!e.altKey && !e.ctrlKey && !e.shiftKey))
					{
						// 避免回车键换行
						e.preventDefault();
						// 下面写你的发送消息的代码
						sendContent();
					}
				})
			}
		})

		
	</script>

	<style>
	.wrap{
		width: 1000px;
		margin: 0 auto;
	}
	</style>
</body>
</html>